package hn.cch.page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 分页标签
 *
 * @author CCH
 * @version 2018.09.25
 */


public class PageTag extends TagSupport {

    //url中的参数
    public static final String CODE = "code";
    public static final String SIZE = "size";


    //页面跳转地址
    private String url;


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public PageTag() {
        super();
        url = null;
    }

    @Override
    public int doStartTag() throws JspException {

        HttpServletRequest request = (HttpServletRequest) super.pageContext.getRequest();
        JspWriter writer = super.pageContext.getOut();

        //分页数据（默认属性：page）
        PageData page = (PageData) request.getAttribute("page");
        if (page == null) {
            return SKIP_BODY;
        }

        //处理网址
        url = resolveUrl(url, pageContext);

        try {
            //计算页面总数
            int total = page.getCount() / PageData.SIZE;
            int other = page.getCount() % PageData.SIZE;
            if (other > 0) {
                total = total + 1;
            }
            writer.print("<nav><ul class=\"pagination\">");

            //显示“上一页”按钮
            if (page.getCode() > 1) {
                String preUrl = append(url, CODE, String.valueOf(page.getCode() - 1));
                writer.print("<li><a href=\"" + preUrl + "\">上一页</a></li>");
            } else {
                writer.print("<li class=\"disabled\"><a href=\"#\">上一页</a></li>");
            }
            //显示五页页码：当前页码的前两页码和后两页码：前后不足两页时显示最前最后num页页码
            int index = 0;
            if ((page.getCode() - 2 >= 1) && (page.getCode() + 2 <= total)) {
                index = page.getCode() - 2;
            } else if (page.getCode() - 2 < 1) {
                index = 1;
            } else if (page.getCode() + 2 > total) {
                int temp = total - 5 + 1;
                index = temp > 0 ? temp : 1;
            }
            for (int i = 1; i <= 5 && index <= total; index++, i++) {
                //当前页码
                if (index == page.getCode()) {
                    writer.print("<li class=\"active\"><a href=\"#\">" + index + "<span class=\"sr-only\">(current)</span></a></li>");
                    continue;
                }
                //要显示的非当前页码
                String pageUrl = append(url, CODE, String.valueOf(index));
                writer.print("<li><a href=\"" + pageUrl + "\">" + index + "</a></li>");
            }
            //显示“下一页”按钮
            if (page.getCode() < total) {
                String nextUrl = append(url, CODE, String.valueOf(page.getCode() + 1));
                writer.print("<li><a href=\"" + nextUrl + "\">下一页</a></li>");
            } else {
                writer.print("<li class=\"disabled\"><a href=\"#\">下一页</a></li>");
            }
            writer.print("</nav>");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }


    /**
     * url追加参数键值对
     *
     * @param url
     * @param key
     * @param value
     * @return
     */
    private String append(String url, String key, String value) {
        //网址为空
        if (url == null || url.trim().length() == 0) {
            return "";
        }
        //?是参数标识符
        if (url.indexOf("?") == -1) {
            url = url + "?" + key + "=" + value;
        } else {
            //&的转义符是&amp; &是参数连接符
            if (url.endsWith("?")) {
                url = url + key + "=" + value;
            } else {
                url = url + "&amp;" + key + "=" + value;
            }
        }
        return url;
    }

    /**
     * UrlSupport.String resolveUrl(String url, String context, PageContext pageContext)
     *
     * @param url
     * @param pageContext
     * @return
     * @throws JspException
     */
    private String resolveUrl(String url, PageContext pageContext) throws JspException {

        Map map = pageContext.getRequest().getParameterMap();
        Set set = map.keySet();
        for (Object key : set) {
            if (CODE.equals(key) || SIZE.equals(key)) {
                continue;
            }
            Object value = map.get(key);
            if (value == null) {
                continue;
            }
            if (value.getClass().isArray()) {
                //数组：取第一个
                url = append(url, key.toString(), ((String[]) value)[0]);
            } else if (value instanceof String) {
                //字符串
                url = append(url, key.toString(), (String) value);
            } else {
                //其他
                url = append(url, key.toString(), value.toString());
            }
        }
        return url;
    }


}
